package team.bluepen.supermarket.data.dao;

import org.apache.hadoop.hbase.util.Bytes;
import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.DatabaseHelper;
import team.bluepen.supermarket.data.dao.abstraction.Repository;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.util.IdGenerator;
import team.bluepen.supermarket.util.Log;
import team.bluepen.supermarket.util.UserChecker;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * {@link User} 存储库
 * @author Kai
 */
public class UserRepository extends Repository<User> {
    private static final String TAG = "UserRepository";

    public UserRepository() {
        super(DatabaseHelper.getUserDatabase());
    }

    /**
     * 创建用户，若用户名已存在返回{@link Error#ERROR_USER_EXISTED}<br>
     * 注意：无需添加ID，本方法自动生成ID。
     * @param user {@link User}
     * @return {@link Error}
     */
    public Error createUser(User user) {
        if(!UserChecker.checkUser(user).getState()) {
            return UserChecker.checkUser(user);
        }
        try {
            List<User> res = database.query(Constant.UserTable.TABLE_FAMILY,
                    Constant.UserTable.QUALIFIER_USERNAME, Bytes.toBytes(user.getUsername()));
            if (res != null && !res.isEmpty()) {
                return Error.ERROR_USER_EXISTED;
            } else {
                user.setId(IdGenerator.generate());
                user.generateRowKey();
                return database.insert(user);
            }
        } catch (IOException e) {
            return Error.ERROR_DATABASE;
        }
    }

    /**
     * 用于修改更新数据
     * @param user 用户
     * @param isUsernameModified 是否修改过用户名
     * @return {@link Error}
     */
    public Error editUser(User user, boolean isUsernameModified) {
        if (!isUsernameModified) {
            return insert(user);
        }

        try {
            List<User> res = database.query(Constant.UserTable.TABLE_FAMILY,
                    Constant.UserTable.QUALIFIER_USERNAME, Bytes.toBytes(user.getUsername()));
            if (res != null && !res.isEmpty()) {
                return Error.ERROR_USER_EXISTED;
            } else {
                return database.insert(user);
            }
        } catch (IOException e) {
            return Error.ERROR_DATABASE;
        }

    }

    /**
     * 验证用户登录信息
     * @param user {@link User} 登录用户
     * @return {@link Error}
     */
    public Error verifyUser(User user) {
        if (user == null) {
            return Error.ERROR_NULL;
        }
        try {
            List<User> res = database.query(Constant.UserTable.TABLE_FAMILY,
                    Constant.UserTable.QUALIFIER_USERNAME, Bytes.toBytes(user.getUsername()));
            if (res.isEmpty()) {
                return Error.ERROR_USER_NOT_EXIST;
            }
            for (User u: res) {
                if (u == null || u.getUsername() == null ||
                        u.getPassword() == null) {
                    return Error.ERROR_NULL;
                }
                if (Objects.equals(u.getUsername(), user.getUsername()) &&
                        Objects.equals(u.getPassword(), user.getPassword())) {
                    user.setRole(u.getRole());
                    user.setRow(u.getRow());
                    user.setId(u.getId());
                    return Error.SUCCESS;
                }
            }
            return Error.ERROR_PASSWORD_NOT_CORRECT;
        } catch (IOException e) {
            Log.e(TAG, "An error occurred in the database while querying. " +
                    "Please check the state of the database.", e);
            return Error.ERROR_DATABASE;
        }
    }
}
